package cn.hdmis.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AbstractAuthenticator;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.annotations.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hdmis.bean.PageBean;
import cn.hdmis.util.JsonValueProcessorImpl;
import cn.hdmis.util.SysMessageBean;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {

	private static final long serialVersionUID = 5880992532144190521L;
	// JSON 内容类型
	public static final String JSON_CONTENT_TYPE = "text/json;charset=UTF-8";
	// XML 内容类型
	public static final String XML_CONTENT_TYPE = "application/xml;charset=UTF-8";
	// HTML 内容类型
	public static final String HTML_CONTENT_TYPE = "text/html;charset=UTF-8";
	// 下载  内容类型
	public static final String BINARY_CONTENT_TYPE = "application/x-download,charset=utf-8";
	
	public static final String MSG_SUCCESS = "success";
	public static final String MSG_FAILED = "failed";
	private String MSG = MSG_SUCCESS;
	// logger
	public final Logger logger  = LoggerFactory.getLogger(getClass());
	
	public PageBean pageBean = new PageBean();

	public void setMSG(String mSG) {
		MSG = mSG;
	}
	public String getMSG() {
		return MSG;
	}
	@JSON(serialize=false)
	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}
	@JSON(serialize=false)
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	@JSON(serialize=false)
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}
	@JSON(serialize=false)
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	@JSON(serialize=false)
	public ServletContext getServletContext() {
		return ServletActionContext.getServletContext();
	}
	@JSON(serialize=false)
	public String getRealyPath(String path) {
		return getServletContext().getRealPath(path);
	}

	/**
	 * TODO:添加提示信息
	 * 
	 * @param messages
	 *            void
	 */
	public void addMessage(String messages) {
		this.addActionMessage(this.getText(messages));
	}

	/**
	 * TODO:添加错误提示信息
	 * 
	 * @param errorMessages
	 *            void
	 */
	public void addError(String errorMessages) {
		this.addActionError(this.getText(errorMessages));
	}

	// 输出JSON数据
	public void responseJson(String json) {
		if(json==null||"[null]".equals(json)||"null".equalsIgnoreCase(json)) json ="";
		HttpServletResponse resp = this.getResponse();
		resp.setContentType(HTML_CONTENT_TYPE);
		try {
			logger.debug("response output:" + json);
			resp.getWriter().write(json.toString());
		} catch (IOException e) {
			logger .error("export JSON 出错：" + e.getMessage());
			if (logger .isDebugEnabled()) {
				logger .error("", e);
			}
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 输出格式化时间的json数据
	 * 
	 * @param obj
	 * 
	 */
	public void sendJSON(Object obj) {
		HttpServletResponse resp = this.getResponse();
		HttpServletRequest request = this.getRequest();
		resp.setContentType(HTML_CONTENT_TYPE);
		JsonConfig jsonConfig = new JsonConfig();
		// 防止自包含
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new JsonValueProcessorImpl());
		// json =null;
		JSONObject json = JSONObject.fromObject(obj, jsonConfig);
		logger .debug(json.toString());
		try {
			PrintWriter out = resp.getWriter();
			boolean scriptTag = false;
			String cb = request.getParameter("callback");
			if (cb != null) {
				scriptTag = true;
				resp.setContentType("text/javascript");
			} else {
				resp.setContentType("application/x-json");
			}
			if (scriptTag) {
				out.write(cb + "(");
			}
			out.print(json.toString());
			if (scriptTag) {
				out.write(");");
			}
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	// 抛出错误页面
	public void sendError(int errorID, CharSequence errorMsg) {
		HttpServletResponse resp = this.getResponse();
		resp.setContentType(HTML_CONTENT_TYPE);
		try {
			resp.sendError(errorID, errorMsg.toString());
		} catch (IOException e) {
			logger .error("输出错误信息 出错：" + e.getMessage());
			if (logger .isDebugEnabled()) {
				logger .debug("", e);
			}
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	protected Map<String, String> uploadFile(File file, String fileFileName)
			throws IOException {
		File f = null;
		String fileDataBasePath = "";
		String filePath = "";
		if (file != null) {
			f = file;
			int indexOfPoint = fileFileName.lastIndexOf(".");
			// 获取上传原文件的后缀名
			String ext = fileFileName.substring(indexOfPoint + 1);
			String root = ServletActionContext.getServletContext().getRealPath(
					"upload");
			// 拼接上传文件名称
			String dateTime = new SimpleDateFormat("yyyyMMddHHmmssssss")
					.format(new Date());
			filePath = root + "/" + dateTime + "." + ext;
			// 存入数据库中的URL路径
			fileDataBasePath = "../upload/" + dateTime + "." + ext;
			FileOutputStream fos = null;
			FileInputStream fis = null;
			fos = new FileOutputStream(filePath);
			fis = new FileInputStream(f);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
			fis.close();
			fos.close();
			Map<String, String> map = new HashMap<String, String>();
			map.put("fileDataBasePath", fileDataBasePath);
			map.put("filePath", filePath);
			return map;
		}
		return null;
	}

	/**
	 * 获取IP
	 * 
	 * @param request
	 * @return String IP
	 */
	public String getIpAddr() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("x-forwarded-for");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip;
	}

	public static String unescape(String src) {
		if (src == null || src.trim().equals(""))
			return "";
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(src
							.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(src
							.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	protected static Map<String, String[]> getParamsMap(String queryString,
			String enc) {
		Map<String, String[]> paramsMap = new HashMap<String, String[]>();
		if (queryString != null && queryString.length() > 0) {
			int ampersandIndex, lastAmpersandIndex = 0;
			String subStr, param, value;
			String[] paramPair, values, newValues;
			do {
				ampersandIndex = queryString.indexOf('&', lastAmpersandIndex) + 1;
				if (ampersandIndex > 0) {
					subStr = queryString.substring(lastAmpersandIndex,
							ampersandIndex - 1);
					lastAmpersandIndex = ampersandIndex;
				} else {
					subStr = queryString.substring(lastAmpersandIndex);
				}
				paramPair = subStr.split("=");
				param = paramPair[0];
				value = paramPair.length == 1 ? "" : paramPair[1];
				try {
					value = URLDecoder.decode(value, enc);
				} catch (UnsupportedEncodingException ignored) {
				}
				if (paramsMap.containsKey(param)) {
					values = paramsMap.get(param);
					int len = values.length;
					newValues = new String[len + 1];
					System.arraycopy(values, 0, newValues, 0, len);
					newValues[len] = value;
				} else {
					newValues = new String[] { value };
				}
				paramsMap.put(param, newValues);
			} while (ampersandIndex > 0);
		}
		return paramsMap;
	}

	/**
	 * 根据时间生成一个随机名称
	 * 
	 * @return
	 */
	public String generateFileNameByDateTime() {
		SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd");
		String fileNameP1 = sdFormat.format(new Date());
		String fileNamep2 = String.valueOf(Math.floor((Math.random() * 10000)));
		if (fileNamep2.contains(".0")) {
			fileNamep2 = fileNamep2.substring(0, fileNamep2.indexOf(".0"));
		}
		return fileNameP1 + "-" + fileNamep2;
	}

	/**
	 * @行为: 销毁session
	 * 
	 * @方法名： destorySession
	 * @返回类型： void
	 */
	public void destorySession(String sessionCrud) {

		this.getSession().removeAttribute(sessionCrud);
	}
	
	public void initPage(){
		String pageSize = this.getRequest().getParameter("numPerPage"); // 每页显示记录数
		String currentPage = this.getRequest().getParameter("pageNum");//当前的页码
		if(pageSize!=null&&pageSize!=""){
			pageBean.setPageSize(Integer.parseInt(pageSize));
		}
		if(currentPage!=null&&currentPage!=""){
			pageBean.setCurrentPage(Integer.parseInt(currentPage));
		}
	}
}
